package pers.wk.queues.headers;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Headers交换机
 */
public class HeadersProducer {

    public static void main(String[] args) {
        //1.ConnectionFactory
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();

            channel.exchangeDeclare(MQConfig.ExchangeName.HEADERS_EXCHANGE, MQConfig.ExchangeType.headers,
                    true, false, false, null);
            System.out.println("headers-生产者启动。。。");

            // 定义队列
            channel.queueDeclare(MQConfig.QueueNames.HEADERS_QUEUE, true, false, false, null);

            // 声明header
            Map<String, Object> bindingHeaders = new HashMap<>();
            /*
                all:代表发送消息时必须匹配header中的所有key/val对
                any:代表发送消息时只需要匹配header中的任意一个key/val对
             */
            bindingHeaders.put("x-match", "any");
            bindingHeaders.put("key1", "147");
            bindingHeaders.put("key2", "258");
            bindingHeaders.put("key3", "369");

            // 将交换机绑定到队列,并指定header信息
            channel.queueBind(MQConfig.QueueNames.HEADERS_QUEUE,
                    MQConfig.ExchangeName.HEADERS_EXCHANGE, "", bindingHeaders);


            String msg = "hello world";

            //x-match值为any时，消息可以被投递到队列中，为all时，无法被投递到此队列中，因为headers不全匹配

            // 发送信息携带的header
            Map<String, Object> requestHeader = new HashMap<>();
            requestHeader.put("key1", "147");
            AMQP.BasicProperties.Builder properties = new AMQP.BasicProperties.Builder();
            properties.headers(requestHeader);

            channel.basicPublish(MQConfig.ExchangeName.HEADERS_EXCHANGE, "",
                    properties.build(), msg.getBytes());
            System.out.println(msg);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }
    }
}
